package edu.gyc.data.struct.stack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class PorlandDemo {
    public static void main(String[] args) {
        //先定义逆波兰表达式
        //(3+4)*-6 ==> 3 4 + 5 * 6 -
        //数字和字符之间用空格隔开
        String suffixExpression="3 4 + 11 * 6 -";
        //先将表达式放到ArrayList
        List<String> list = getListString(suffixExpression);
        System.out.println("porlandString:" + list);
        int r = calculate(list);
        System.out.println("Result: r=" + r);
    }

    public static List<String> getListString(String expression) {
        String [] strings=expression.split(" ");

         return Arrays.asList(strings);

    }

    public static int calculate(List<String> list) {
        //创建栈
        Stack<String > stack=new Stack<>();
        for (String s:
             list) {
            if(s.matches("\\d+")){//匹配的是多位数
                stack.push(s);
            }else {
                //pop两个数，运算，再入栈
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int r=0;
                if (s.equals("+")) {
                    r=num1+num2;
                } else if (s.equals("-")) {
                    r=num1-num2;
                } else if (s.equals("*")) {
                    r=num1*num2;
                } else if (s.equals("/")) {
                    r=num1/num2;
                }else {
                    throw new RuntimeException("运算符有误！");
                }
                //将结果入栈
                stack.push(String.valueOf(r));
            }
        }
        return Integer.parseInt(stack.pop());
    }
}
